package Net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-15
 * Time: 16:54
 */
public class TcpServer {
    //创建服务器使用的serverSocket--用于接收和发送TCP报文
    ServerSocket serverSocket = null;

    public TcpServer(int port) throws IOException {
        //服务器需要指定端口号
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        while(true){//一直保持开启状态,等待客户端与服务器连接
            Socket clientSocket = serverSocket.accept();
            Thread t = new Thread(()->{
                try {
                    processConnect(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }

    public void processConnect(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d] 建立连接\n",clientSocket.getInetAddress(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while(true){
                Scanner scanner = new Scanner(inputStream);
                PrintWriter printWriter = new PrintWriter(outputStream);
                if(!scanner.hasNext()){
                    //如果读到结束符,则结束连接
                    System.out.printf("[%s : %d] 结束连接\n",clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                //读取请求并解析
                String request = scanner.next();
                //根据请求做出响应
                String response = process(request);
                //将响应发送给客户端
                printWriter.println(response);
                //刷新缓冲区
                printWriter.flush();
                System.out.printf("[%s : %d] req = %s ; rep = %s 发送成功\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        }finally {
            //关闭资源
            clientSocket.close();
        }
    }
    //回显服务器,做出啥请求,就返回啥响应
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer(8000);
        tcpServer.start();
    }

}
